package com.dao;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

@Repository
public class GoodsDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public Float queryPriceById(Integer id) {
        String sql = "SELECT price FROM goods WHERE goods_id = ?";
        Float price = jdbcTemplate.queryForObject(sql, Float.class, id);
        return price;
    }

    public void updateBalance(Integer userId, Float money) {
        String sql = "UPDATE user_account SET money = money - ? WHERE user_id = ?";
        jdbcTemplate.update(sql,money,userId);
    }

    public void updateAmount(Integer goods_id, int amount){
        try{
            String sql = "UPDATE goods_amount SET goods_num = goods_num - ? WHERE goods_id = ?";
            jdbcTemplate.update(sql,amount,goods_id);
            // 模拟一个异常，回答升数据库数据不一致现象
            //int i = 10 / 0;
        }catch (Exception e){
            System.out.println("发生异常了,要进行回滚");
            // 发生异常，回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

    }

    public Float queryPriceById02(Integer id) {
        String sql = "SELECT price FROM goods WHERE goods_id = ?";
        Float price = jdbcTemplate.queryForObject(sql, Float.class, id);
        return price;
    }

    public void updateBalance02(Integer userId, Float money) {
        //故意写错的
        //String sql = "UPDATEXX user_account SET money = money - ? WHERE user_id = ?";
        String sql = "UPDATE user_account SET money = money - ? WHERE user_id = ?";
        jdbcTemplate.update(sql,money,userId);
    }

    public void updateAmount02(Integer goods_id, int amount){
        try{
            String sql = "UPDATE goods_amount SET goods_num = goods_num - ? WHERE goods_id = ?";
            jdbcTemplate.update(sql,amount,goods_id);
            //int i = 10 / 0;
        }catch (Exception e){
            System.out.println("发生异常了,要进行回滚");
            // 发生异常，回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    }

}
